package com.zsk.shop.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zsk.shop.api.apple.AppleUtil;
import com.zsk.shop.api.apple.UserInfoApple;
import com.zsk.shop.common.base.BaseResponse;
import com.zsk.shop.common.utils.ToolUtil;
import com.zsk.shop.entity.ShopUser;
import com.zsk.shop.model.results.AppUserDecodeResult;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;

/**
 * @author ljh
 * @create 2021/7/22 10:09
 */
@Service
public class AppleDecodeService {

    private static final Logger logger = LoggerFactory.getLogger(AppleDecodeService.class);

    @Resource
    private ShopUserService userService;

    @Resource
    private BaseService baseService;

    @Transactional(rollbackFor = Exception.class)
    public BaseResponse<AppUserDecodeResult> appleDecode(String identityToken) {
        try {
            //对identityToken解码
            JSONObject json = AppleUtil.parserIdentityToken(identityToken);
            if (json == null) {
                return BaseResponse.error("授权解码失败");
            }
            UserInfoApple userInfoApple = JSONObject.parseObject(json.toJSONString(), UserInfoApple.class);
            if (ToolUtil.isEmpty(userInfoApple)) {
                return BaseResponse.error("当前授权方法有误！");
            }
            ShopUser user = userService.appleLogin(userInfoApple);
            logger.warn("APPLE登录result(如果为空则失败)" + JSON.toJSONString(user));
            if (ToolUtil.isEmpty(user)) {
                return BaseResponse.error("当前第三方APPLE授权获取信息错误，登入失败！");
            }
            return BaseResponse.success("APPLE登录成功", baseService.getDecodeResult(user));
        } catch (Exception e) {
            logger.error("app appleLogin error:" + e.getMessage(), e);
            return BaseResponse.error("系统错误");
        }
    }
}
